<?php
declare (strict_types=1);

namespace app\controller;

use app\BaseController;
use app\common\constant\ErrorNum;
use app\common\exception\AppException;
use app\model\AdminUser;
use think\Request;

class Login extends BaseController
{
    protected $middleware = [];

    public function index()
    {
        if ($this->isLogin()) {
            return redirect(url('index/index')->__toString());
        }
        return view();
    }

    /**
     * 登录
     * @param Request $request
     * @return \think\Response
     * @throws AppException
     */
    public function login(Request $request): \think\Response
    {
        $inputData = $request->param();
        if (!isset($inputData['mobile']) || !isset($inputData['password'])) {
            throw new AppException('参数错误', ErrorNum::PARAM_ILLEGAL);
        }
        $userModel = new AdminUser();
        $where['mobile'] = $inputData['mobile'];
        $userInfo = $userModel->getUserInfo($where);
        if ($userInfo->isEmpty()) {
            throw new AppException('用户未注册', ErrorNum::NO_USER);
        }
        if ($userInfo['password'] != md5($inputData['password'] . $userInfo['salt'])) {
            throw new AppException('密码错误', ErrorNum::ERROR_PASSWORD);
        }
        session('uid', $userInfo['id']);
        session('user_info', $userInfo);
        return $this->outputSuccess();
    }

}
